package com.reider.log4AS3.appenders
{
	import com.reider.log4AS3.dataholder.Log;
	import com.reider.log4AS3.event.LocalEvent;
	import com.reider.log4AS3.utils.BufferedCaller;
	import com.reider.log4AS3.utils.LocalConnecter;
	import com.reider.log4AS3.utils.ObjectTracer;
	
	import flash.events.Event;
	
	public class LogWindowAppender extends Appender
	{
		private var localConnecter:LocalConnecter
		private var conTarget:Object
		private var bufferTarget:Object
		private var sendLogBuffer:BufferedCaller
		
		//--------------------------------------------------------------------------
	    //
	    //  Constructor
	    //
	    //--------------------------------------------------------------------------
		
		public function LogWindowAppender(name:String)
		{
			super(name);
			
			conTarget = new Object()
			bufferTarget = new Object()
			bufferTarget.sendLog = sendLog
			
			localConnecter = new LocalConnecter("_appenderConn_log4as3", "_logWindowConn_log4as3", conTarget)
			localConnecter.addEventListener(LocalEvent.CONNECT, onConnect)
			localConnecter.addEventListener(LocalEvent.STATUS, onStatus)
			localConnecter.connect()
			
			sendLogBuffer = new BufferedCaller(bufferTarget,localConnecter,LocalEvent.CONNECT)
		}
		
		//--------------------------------------------------------------------------
	    //
	    //  Public methods
	    //
	    //--------------------------------------------------------------------------
		
		override public function print(log:Log):void
		{
			sendLogBuffer.sendLog(log)
		}
		
		//--------------------------------------------------------------------------
	    //
	    //  Private methods
	    //
	    //--------------------------------------------------------------------------
	    
	    private function sendLog(log:Log):void
	    {
	    	var logObj:Object = log.toObject()
	    	var debugObjs:Array = new Array()
	    	for(var i:int=0; i<log.additionalArgs.length; i++){
	    		var obj:Object = log.additionalArgs[i]
	    		debugObjs.push( ObjectTracer.objectToHierearchy(obj,[]) )
	    	}
	    	logObj.hierarchy = debugObjs
	    	
	    	localConnecter.callFunction("onLogArrived", logObj)
	    }
	    
	    //--------------------------------------------------------------------------
	    //
	    //  Callback methods
	    //
	    //--------------------------------------------------------------------------
		
		private function onConnect(event:Event):void
		{
			trace("---- connect")
		}
		
		private function onStatus(event:LocalEvent):void
		{
			trace("---- status "+event.statusObj.level)
		}

	}
}